package com.tanker.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.Map;

/**
 * @author xqxue
 * @time 2018年7月20日 下午1:17:42
 */
public class JsonUtils {

	public static String toJson(Object bean) {
		Gson gs = new Gson();
		return gs.toJson(bean);
	}

	public static Object fromJson(String json, Class clazz) {
		Gson gs = new Gson();
		return gs.fromJson(json, clazz);
	}

	public static String object2Json(Object obj) {
		String result = null;
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			result = objectMapper.writeValueAsString(obj);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static Map object2Map(Object obj) {
		String object2Json = object2Json(obj);
		Map<?, ?> result = jsonToMap(object2Json);
		return result;
	}

	/**
	 * <p>
	 * JSON字符串转Map对象
	 * </p>
	 */
	public static Map<?, ?> jsonToMap(String json) {
		return json2Object(json, Map.class);
	}

	/**
	 * <p>
	 * JSON转Object对象
	 * </p>
	 *
	 */
	public static <T> T json2Object(String json, Class<T> cls) {
		T result = null;
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			result = objectMapper.readValue(json, cls);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return result;
	}


	public static <T> T conveterObject(Object srcObject, Class<T> destObjectType) {
		String jsonContent = object2Json(srcObject);
		return json2Object(jsonContent, destObjectType);
	}

}
